#include "WordCounterTable.h"
#include "ManualHash.h"

#include <iostream>
#include <fstream>

using namespace std;

WordCounterTable::WordCounterTable()
{
}

WordCounterTable::~WordCounterTable()
{
}

void WordCounterTable::addWordCounter(string word, string doc)
{
	uint word_key = ManualHash::ToInteger(word);
	map<uint,vector<WordCounter> >::iterator it;
	it = wordCounterTable.find(word_key);	
	
	// se a insercao  sequencial em ordem crescente de numero do documento temos
	
	//Existe tal palavra no hash?
	if (it != wordCounterTable.end())
	{
		// Ja existe esta palavra no doc?
		if (it->second.back().doc == doc)
		{
			it->second.back().n++;
		}			
		else
		{
			WordCounter wd;
			wd.doc = doc;
			wd.n = 1;
			it->second.push_back(wd);
		}
	}
	// Se nao houver, criar entrada
	else
	{
		WordCounter wd;
		wd.doc = doc;
		wd.n = 1;
		vector<WordCounter> v;
		v.push_back(wd);
		wordCounterTable[word_key] = v;	
	}
}

void WordCounterTable::saveWordCounterTable(ofstream* file)
{
	if(file->is_open())
	{
		
		map<uint,vector<WordCounter> >::iterator it;
		//map<uint,std::string>::iterator hi;
		*file << 0;
		//for (it = wordCounterTable.begin(),hi = hashmap.begin();it != wordCounterTable.end(), hi != hashmap.end(); hi++,it++)
		for (it = wordCounterTable.begin();it != wordCounterTable.end(); it++)
		{
			//*file << hi->first << " " ;
			//*file << hi->second << " " ;
			*file << endl;
			*file << it->first << " " ;			
			for(vector<WordCounter>::iterator vi = it->second.begin();vi != it->second.end();vi++)
				*file << " " << vi->doc << " " << vi->n  ;
			*file << " " << 0;
		}
	}
}
